package toy.keli.edic.ui.home.homescreen

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.google.accompanist.glide.rememberGlidePainter
import toy.keli.edic.data.GlobalVal
import toy.keli.edic.data.config.MenuConf
import toy.keli.edic.data.config.PageConf
import toy.keli.edic.data.config.PageConf.DicType
import toy.keli.edic.data.local.entity.Meaning
import toy.keli.edic.data.local.entity.Meaning.Companion.typeMap
import toy.keli.edic.data.model.Book
import toy.keli.edic.data.model.WordExtend
import toy.keli.edic.domain.model.WordModel
import toy.keli.edic.ui.home.HomeEvents
import toy.keli.edic.ui.home.dictionaryStringBuilder
import toy.keli.edic.ui.level.LevelViewModel
import toy.keli.edic.ui.main.components.InfoDialog
import toy.keli.edic.ui.main.components.TopDialog
import toy.keli.edic.ui.main.components.ViewButton
import toy.keli.edic.ui.main.extend.bgRun
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.view.ClickAbelText
import java.util.Locale

/**
 * 首页单词的详细内容
 */
@Composable
@Preview(showBackground = true)
fun DefaultPageWordDetail(
    wordModel: WordModel?=WordModel.demoModel,
    pic:String="imgs/hi.jpg",
) {
    if( LocalInspectionMode.current) {
        ActivityRun.context = LocalContext.current
    }
    val tColor = MaterialTheme.colorScheme.onBackground
    val bColor = MaterialTheme.colorScheme.background
    val data = remember {  WordDetailData(wordModel,tColor)}
    data.apply {
        if(!LocalInspectionMode.current) {
            val levelViewModel: LevelViewModel = hiltViewModel()
            LaunchedEffect(wordModel?.word) {
                if (wordModel?.word == null) return@LaunchedEffect
                if (lName.length > 0 && lName != wordModel.word) {
                    moreVisible = false
                }
                lName = ""
                bgRun {
                    levelViewModel.getLevel(wordModel) {
                        lName = it
                    }
                }
            }
        }
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(18.dp, 10.dp, 18.dp, 36.dp)
        ) {
            if(pic.length>0) {
                Image(
                    painter = rememberGlidePainter(request = pic),
                    contentDescription = "pic",
                    modifier = Modifier
                        .size(100.dp)
//                        .border(1.dp, Color.Gray)
                        .clickable {
                            InfoDialog.show {
                                Image(
                                    painter = rememberGlidePainter(request = pic),
                                    contentDescription = "pic",
                                    modifier = Modifier.fillMaxWidth()
                                )
                            }
                        }
                )
            }

            //中文意思
            Text(
                text = "${wordModel?.ch ?: "word.ch"}",
                //fontStyle = FontStyle.Italic,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                lineHeight = TextUnit(20f, TextUnitType.Sp),
                style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Normal),
                color = tColor,
                modifier = Modifier
                    .clickable {
                        showCh = !showCh
                    }
                    .padding(bottom = 15.dp)
            )
            val yb = wordModel?.getYinBiao()
            if(yb!=null && yb.size>0) {
                toy.keli.edic.ui.main.components.FlowRow {
                    if (yb != null) {
                        voice("美", yb!!)
                        Spacer(Modifier.width(7.dp))
                        voice("英", yb)
                    }
                }
            }
            //级别
            Text(
                text = lName,
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Start,
                color = Color.Blue,
                modifier = Modifier.padding(vertical = 15.dp)
                .clickable {
                    TopDialog(lName,wordModel?.word?:""){
                        GlobalVal.wordViewModel.searcher(it)
                    }
                //    GlobalVal.nav.navigate(NavScreen.LevelScreen.route) {
                //        launchSingleTop = true
                //    }
                }
            )
            wordModel?.meanings?.forEachIndexed { index, meaning ->
                runOneMeaning(index, meaning)
            }

            extendButton()
            //wordModel?.meanings?.subList(0,moreN)!!.forEachIndexed { index, meaning ->
            //    runOneMeaning(index, meaning)
            //}
            //if (!moreVisible) {
            //    Text(
            //        mt("more"),
            //        color = tColor,
            //        modifier = Modifier.align(Alignment.End).clickable {
            //                moreVisible = true
            //            }
            //    )
            //} else {
            //    wordModel?.meanings?.subList(moreN, mSize)?.forEachIndexed { index, meanning ->
            //        runOneMeaning(index + moreN, meanning)
            //    }
            //}


        }
    }
}
class WordDetailData(val wordModel: WordModel?, val tColor: Color) {

    val dicType = PageConf.getInt(PageConf.homePage.DicType, 2)
    var showCh by   mutableStateOf(
            listOf(
                DicType.en_cn.ordinal,
                DicType.encn.ordinal
            ).contains(dicType)
        )
    val showEn = listOf(DicType.en_en.ordinal, DicType.encn.ordinal).contains(dicType)
    val moreN = 3
    var mSize = 0
    var moreVisible by mutableStateOf(true)
    //级别
    var lName by  mutableStateOf("Top0(95,6%,1/17)小学一年级")
    val TAG = "WordDetailData"
    init{
        if(wordModel?.meanings!=null) mSize =wordModel?.meanings!!.size
        dictionaryStringBuilder = dictionaryStringBuilder.clear()
        dictionaryStringBuilder.append(wordModel?.word).append("\n")
        if(mSize==1 && wordModel?.meanings!![0].def==null){
            moreVisible = true
        }
    }

    @Composable
    fun runOneMeaning(index:Int, meaning:Meaning){
        val defChVisable = remember {  mutableStateOf(false) }
        val examChVisable =  remember { mutableStateOf(false) }
        val dEn =  remember { mutableStateOf(false) }
        val eEn =   remember {  mutableStateOf(false) }

        dictionaryStringBuilder.append(meaning.speechPart).append("\n")
        var typeName =""
        var typeZhName =""

        if (meaning.speechPart != null) {
            typeName = "("+meaning.speechPart+")"
            if(meaning.speechPart in typeMap.keys){
                typeZhName = "("+typeMap[meaning.speechPart]+")"
            }
//                    Text(
//                        text = meaning.speechPart,
//                        style = MaterialTheme.typography.titleSmall,
//                        fontWeight = FontWeight.Bold,
//                        textAlign = TextAlign.Start,
//                        color = MaterialTheme.colorScheme.onSurface
//                    )
        }

        dictionaryStringBuilder.append("${index + 1}. ${meaning.def}").append("\n")

        if ((showCh || defChVisable.value) && meaning.def_ch != null) {
            var defch = ""
            if(meaning.def_ch!=null){
                defch = if(meaning.def_ch.startsWith("（")) meaning.def_ch.substring(1,meaning.def_ch.length-2) else meaning.def_ch
            }
            Text(text = "${index + 1}. $typeZhName " + defch, modifier = Modifier.clickable {
                if (dicType == DicType.en_cn.ordinal) {
                    dEn.value = !dEn.value
                }
            }, color = tColor)
        }
        if ((showEn || dEn.value) && meaning.def != null) {
            ClickAbelText(
                text = "${typeName} " + (if(meaning.def==null) "" else meaning.def),
                style = MaterialTheme.typography.titleSmall,
                lineHeight = TextUnit(18f, TextUnitType.Sp),
                color = tColor,
                onDbClick = {
                    defChVisable.value = !defChVisable.value
                }
            )
        }
        if (!meaning.labels.isNullOrEmpty()) {
            val label = meaning.labels.map { label -> label.name }.toString()
                .removePrefix("[")
                .removeSuffix("]").replace(",", " •")
            dictionaryStringBuilder.append(label).append("\n")
            Text(
                text = label,
                fontStyle = FontStyle.Italic,
                style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Normal),
                color = Color.Gray
            )
        }
        if (!meaning.example.isNullOrEmpty()) {
            val etitle = when (dicType) {
                0 -> "Example: "
                else -> "例句: "
            }
            val example = etitle + "${meaning.example}"
            dictionaryStringBuilder.append(example).append("\n")
            if ((showCh || examChVisable.value) && meaning.example_ch != null) {
                Text(text =etitle+ meaning.example_ch, modifier = Modifier.clickable {
                    eEn.value = !eEn.value
                })
            }
            ClickAbelText(
                text = example,
                fontStyle = FontStyle.Italic,
                lineHeight = TextUnit(16f, TextUnitType.Sp),
                style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Normal),
                color = Color.Gray,
                onDbClick = {
                    examChVisable.value = !examChVisable.value
                }
            )
        }
        if (!meaning.synonyms.isNullOrEmpty()) {
            val snomon = when (dicType) {
                0 -> "Synonym(s)"
                else -> "同义词"
            }
            val synonym = "${snomon}: ${
                meaning.synonyms.toString()
                    .removePrefix("[")
                    .removeSuffix("]")
            }"
            dictionaryStringBuilder.append(synonym).append("\n")
            ClickAbelText(
                text = synonym,
                fontStyle = FontStyle.Italic,
                lineHeight = TextUnit(16f, TextUnitType.Sp),
                style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Normal),
                color = Color.Gray
            )
        }
        Spacer(modifier = Modifier.height(4.dp))
        Divider(
            thickness = 0.4.dp,
            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.2f)
        )
        Spacer(modifier = Modifier.height(4.dp))
    }

    @Composable
    fun voice(type:String="美",yb:Map<String,String>){
        if(yb.get(type)==null || yb.get(type)?.length==0) return
        var enable by remember { mutableStateOf(0) }
        var typeText by remember {  mutableStateOf( type) }
        Column (modifier = Modifier.padding(5.dp)) {
            Row(
                modifier = Modifier
                    .background(Color.LightGray, shape = CircleShape)
                    .padding(5.dp)
                    .clickable(onClick = {
                        enable++
                        if (enable == 1) {
                            bgRun {
                                do {
                                    if (typeText != type) typeText = enable.toString()
                                    GlobalVal.tts.play(
                                        wordModel?.word!!,
                                        if (type == "美") Locale.US else Locale.UK
                                    )
                                } while (--enable > 0)
                                typeText = type
                            }
                        } else {
                            typeText = enable.toString()
                        }
                    })
            ) {
                Text(
                    typeText, color = Color.White, modifier = Modifier
                        .drawBehind {
                            drawCircle(color = Color(255, 153, 16), 28f)
                        }
                )
                Text(
                    yb.get(type)!!,
                    fontStyle = FontStyle.Italic,
                    color = Color.Gray,
                    modifier = Modifier
                        .padding(horizontal = 5.dp)
                )
//            Icon(painter = painterResource(R.drawable.speak),"play", modifier = Modifier
//                .size(20.dp)
//            )
            }
        }
    }

    @Composable
    fun extendButton(){
        Row {
            val ex =  if(LocalInspectionMode.current) WordExtend() else  Book.wordEx()
            val name = wordModel?.word.toString()
            if (ex.data.size + ex.isize > 2) {
                ViewButton("wordScapesGame") {
                    HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.wordScapesGame)
                }
            }

            if (ex.esize > 2 && ex.extword.filter { it.indexOf(name) > -1 }.size>1) {
                ViewButton("wordExtGame") {
                    HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.wordExtGame)
                }
            }

            ViewButton("jdc_main") {
                HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.jdc_main)
            }
        }
    }
}
